<template>
  <view class="hform-item-wrap">
    <view :class="[error ? 'hform-item hform-item-error': 'hform-item']">
      <view class="hform-item-required" v-show="required">*</view>
      <text class="hform-item-label" :style="{width: labelWidth+'rpx'}">{{label}}</text>
      <slot></slot>
    </view>
    <h-toast/>
  </view>
</template>
<script>
import AsyncValidator from 'async-validator'
import hToast from "../hToast/index.vue";
export default {
  name: "hFormItem",
  components: {hToast},
  inject: ['hForm'],
  provide() {
    return {
      hFormItem: this
    }
  },
  props: {
    label: {
      type: String,
      default: ''
    },
    prop: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      required: false,
      error: false
    }
  },
  mounted() {
    this.hForm.handleAddField(this)
    let formInitValue = this.hForm.initModelValue
    if(this.prop) {
      this.initialValue = formInitValue[this.prop]
      this.setRules();
    }
  },
  onShow() {
    this.hForm.handleAddField(this)
    let formInitValue = this.hForm.initModelValue
    if(this.prop) {
      this.initialValue = formInitValue[this.prop]
      this.setRules();
    }
  },
  computed: {
    fieldValue() {
      return this.hForm.model[this.prop]
    },
    labelWidth() {
      return this.hForm.labelWidth || 120
    }
  },
  methods: {
    setRules() {
      let rules = this.getRules();
      if (rules.length) {
        rules.forEach(rule => {
          if (rule.required !== undefined) this.required = rule.required
        });
      }
      // this.$on('form-blur', this.onFieldBlur);
      // this.$on('form-change', this.onFieldChange);
    },
    getRules() {
      let formRules = this.hForm.rules;
      formRules = formRules && this.prop ? formRules[this.prop] : [];
      return formRules;
    },
    // 过滤出符合要求的 rule 规则
    getFilteredRule (trigger) {
      const rules = this.getRules();
      return rules.filter(rule => !rule.trigger || rule.trigger.indexOf(trigger) !== -1);
    },
    /**
     * 校验表单数据
     * @param trigger 触发校验类型
     * @param callback 回调函数
     */
    validate(trigger, cb) {
      let rules = this.getFilteredRule(trigger);
      if(!rules || rules.length === 0) {
        if (cb) cb(true);
        return true;
      }
      // 使用 async-validator
      if(this.prop) {
        const validator = new AsyncValidator({ [this.prop]: rules });
        let model = {[this.prop]: this.fieldValue};
        validator.validate(model, { firstFields: true }, errors => {
          if(errors) {
            this.error = true
          }
          else {
            this.error = false
          }
          let message = errors ? errors[0].message : '';
          if (cb) cb(message);
        })
      }

    },
    resetField () {
      if(this.prop) {
        this.hForm.model[this.prop] = this.initialValue;
        this.error = false
      }
    },
    onFieldBlur(val) {
      if(this.prop) {
        this.hForm.model[this.prop] = val
      }
      this.validate('blur');
    },
    onFieldChange(val) {
      if(this.prop) {
        this.hForm.model[this.prop] = val
      }
      this.validate('change');
    },
  },
}
</script>

<style>
.hform-item-wrap {
  padding: 0 20rpx;
}
.hform-item-required {
  color: #f84e4e;
  height: auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-top: 10rpx;
  margin-right: 10rpx;
}
.hform-item {
  width: 100%;
  height: auto;
  padding: 20rpx 0;
  display: flex;
  border-bottom: 1px solid #efefef;
  align-items: center;
  transition: all linear .3s;
}
.hform-item-label {
  font-size: 28rpx;
  margin-right: 10rpx;
  width: 120rpx;
}
.hform-item-error {
  border-bottom: 1px solid #f84e4e;
}
</style>
